package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.zsmart.core.exception.BaseAppException;
import com.ztesoft.zsmart.core.log.ZSmartLogger;
import com.ztesoft.zsmart.core.util.JsonUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Classname TransactorAttachHandler
 * @Description 经办人附件渲染，value是json格式，valueDesc取json中的fileName属性值
 * @Author zhang.song
 * @Date 2021-08-23 11:34
 */
@Service
public class TransactorAttachHandler extends AbstractAttrHandler {

    private static final ZSmartLogger LOGGER = ZSmartLogger.getLogger(TransactorAttachHandler.class);

    @Override
    public void init(CommonAttrVO commonAttrVO) {

    }

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        if (KiteStringUtils.isNotEmpty(value) && KiteStringUtils.isJsonArray(value)) {
            List<Map> attachs = null;
            try {
                attachs = JsonUtil.json2List(value, Map.class);
            } catch (BaseAppException e) {
                LOGGER.warn("经办人附件value转JsonArray报错", e);
            }

            if(KiteListUtils.isNotEmpty(attachs)) {
                StringBuffer sb = new StringBuffer();
                attachs.forEach(attach -> {
                    if(KiteStringUtils.isNotEmpty(MapUtils.getString(attach, "fileName"))) {
                        sb.append(",").append(MapUtils.getString(attach, "fileName"));
                    }
                });
                if(sb.length() > 0) {
                    valueDesc = sb.substring(1);
                }
            }
        }
        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }
}
